public class ListNode {
    int val;
    ListNode next;
    ListNode() {}
    ListNode(int val) { this.val = val; }
    ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}

class MySolution1 {
    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        ListNode head = null;
        ListNode tail = null;
        if (list1 == null && list2 == null) {
            return list1;
        }
        if (list1 == null && list2 != null) {
            return list2;
        }
        if (list1 != null && list2 == null) {
            return list1;
        }
        while (list1 != null && list2 != null) {
            if (list1.val > list2.val) {
                if (head == null) {
                    head = tail = new ListNode(list2.val);
                    tail.next = new ListNode(list1.val);
                    tail = tail.next;
                } else {
                    tail.next = new ListNode(list2.val);
                    tail = tail.next;
                    tail.next = new ListNode(list1.val);
                    tail = tail.next;
                }
            } else {
                if (head == null) {
                    head = tail = new ListNode(list1.val);
                    tail.next = new ListNode(list2.val);
                    tail = tail.next;
                } else {
                    tail.next = new ListNode(list1.val);
                    tail = tail.next;
                    tail.next = new ListNode(list2.val);
                    tail = tail.next;
                }
            }
            list1 = list1.next;
            list2 = list2.next;
        }
        return head;
    }
}